<template>
  <div class="start-check">
    <head-top head-title="开始查验" hidden='true' go-back="true"></head-top>
    <div class="back" @click="back"></div>
    <h3 class="theme border-bottom">{{upName}}</h3>
    <ul class="wrapper">
      <li class="pic-desc-wrapper border-bottom" v-for="(item, index) in listData" :key="index">
        <p class="title">{{item.category_name}}</p>
        <mt-button class="btn" type="primary"
                   v-show="item.status === 0"
                   @click.native="submitCheck(item.category_id, $route.params.liftNum, item.resolvent, serverId, relatedId)">
          <span>提交</span>
        </mt-button>
        <mt-button class="btn" type="primary" style="backgroundColor: #ccc" v-show="item.status === 1">
          <span>已提交</span>
        </mt-button>
        <mt-button class="btn" type="primary"
                   @click.native="resetEveryCheck(item.id, item.resolvent, serverId, item.img)"
                   v-show="(serverId.length || showText || showImage) && showId === item.category_id && item.status === 1">
          <span>重新提交</span>
        </mt-button>
        <ul>
          <!-- <li v-show="true" class="line"> -->
          <li class="line" v-show="image" v-for="(image,index) in item.img" :key="index">
            <div class="img_size">
              <div :style="'backgroundImage:url('+image+')'" class="picture" @click="preview(index)"></div>
              <!-- <div class="picture" @click="preview(index)"></div> -->
              <!-- <span @click='item.img.splice(index, 1); showImage = true' class="remove">x</span> -->
              <span @click='deleteEveryImage(item.img, index, item.category_id)' class="remove">x</span>
              <!-- <input class="desc" type="text" placeholder="请输入存在的问题"> -->
            </div>
          </li>
          <li class="line" v-show="image && !isIOS && showId === item.category_id"
              v-for="(image,index) in images.localId" :key="index">
            <div class="img_size">
              <div :style="'backgroundImage:url('+image+')'" class="picture" @click="preview(index)"></div>
              <!-- <div class="picture" @click="preview(index)"></div> -->
              <span @click='delImage(index)' class="remove">x</span>
              <!-- <input class="desc" type="text" placeholder="请输入存在的问题"> -->
            </div>
          </li>
          <li class="line" v-show="image && isIOS && showId === item.category_id"
              v-for="(image,index) in images.iosLocalId" :key="index">
            <!-- <li v-show="true" class="line"> -->
            <div class="img_size" ref="showImage">
              <div :style="'backgroundImage:url('+image+')'" class="picture" @click="preview(index)"></div>
              <!-- <div class="picture" @click="preview(index)"></div> -->
              <span @click='delImageIOS(index)' class="remove">x</span>
              <!-- <input class="desc" type="text" placeholder="请输入存在的问题">            -->
            </div>
          </li>
          <!-- <li class="pic-desc" @click="addImageDesc(item.category_id)">
            <img class="pic" src="../common/images/tianjiatupian@2x.png" alt="" width="55" height="55">
            <span class="desc">请简单描述存在的问题</span>
          </li> -->
          <li class="input-container" @click="addImageDesc(item.category_id)">
            <img class="pic" src="../common/images/tianjiatupian@2x.png" alt="" width="55" height="55">
          </li>
        </ul>
        <div class="limit">
          (拍照上传照片，最多上传3张照片)
        </div>
        <div class="desc">
          <textarea @focus="getFocus(item.resolvent, item.category_id)" @keyup="writeContent(item.resolvent)"
                    @input="writeContent(item.resolvent)" name="" id="" cols="30" rows="10" v-model="item.resolvent"
                    @change="getContent(item.resolvent, item.category_id)" maxlength="100"
                    placeholder="请输入存在的问题"></textarea>
          <div class="count" v-show="showId === item.category_id && showText">
            {{currentCount}}/{{totalCount-currentCount}}
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
  import headTop from '../header/Header.vue'
  import wx from 'weixin-js-sdk'
  import { getCheckContent, submitEveryCheck, editVeryCheck } from '../../api/jianli.js'
  import qs from 'qs'
  import commonUrl from '../../common/js/commonUrl.js'
  import { Toast } from 'mint-ui'

  export default {
    name: 'StartCheck',
    data () {
      return {
        images: {
          localId: [],
          iosLocalId: []
        },
        maxSize: 0,
        ready: false,
        isIOS: false,
        serverId: [],
        listData: [],
        showId: '',
        totalCount: 100,
        currentCount: 0,
        relatedId: '',
        content: '',
        upName: '',
        showText: false,
        showImage: false,
        img: [],
        status: ''
      }
    },
    components: {
      headTop
    },
    // created() {
    //   this.totalCount = 100
    //   this.currentCount = 0
    // },
    mounted () {
      // 初始化JSConfig
      const urlLink = `${commonUrl.apihost}index.php/wx/wx_jssdk/getSignPackage`
      let data = {
        url: window.location.href.split('#')[0]
      }
      this.$http.post(urlLink, qs.stringify(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
        if (res.data.code === 200) {
          wx.config({
            debug: true,
            appId: res.data.data.appId,
            nonceStr: res.data.data.nonceStr,
            rawString: res.data.data.rawString,
            signature: res.data.data.signature,
            timestamp: res.data.data.timestamp,
            jsApiList: ['chooseImage', 'previewImage', 'getLocalImgData', 'uploadImage']
          })
          this.ready = true
        }
      })
    },
    created () {
      this._getCheckContent()
    },
    methods: {
      getFocus (content, id) {
        this.showId = id
        this.showText = true
        this.currentCount = content.length
      },
      deleteEveryImage (img, index, id) {
        this.showId = id
        img.splice(index, 1)
        this.img = img
        this.showImage = true
      },
      writeContent (content, id) {
        this.currentCount = content.length
        let remainCount = this.totalCount - this.currentCount
        if (!remainCount) {
          Toast({
            message: '字数不能超过200',
            position: 'middle',
            duration: 1000
          })
        }
      },
      _getCheckContent () {
        getCheckContent(this.$route.params.id, this.$route.params.liftNum, this.$route.params.name).then(res => {
          if (res.code === 200) {
            this.listData = res.data.data
            // this.listData.forEach(item => {
            //   this.$set(item, 'resolvent1', '')
            // })
            this.relatedId = res.data.related_id
            this.upName = res.data.up_name
          }
        })
      },
      back () {
        history.replaceState({}, '', '/Check')
        this.$router.push('/CheckPublish')
      },
      addImageDesc (id) {
        if ((this.images.localId.length || this.images.iosLocalId.length) && this.showId != id) {
          Toast({
            message: '请先提交上一条数据',
            position: 'middle',
            duration: 1000
          })
          return
        }
        if (this.showId != id) {
          this.images.localId = []
          this.images.iosLocalId = []
        }
        this.showId = id
        if (this.ready) {
          var self = this
          var currentSize = this.images.localId.length + this.img.length
          if (self.isIOS) {
            if (this.images.iosLocalId.length + this.img.length > 2) {
              alert('图片不能超过3张')
              return
            }
          } else {
            if (this.images.localId.length + this.img.length > 2) {
              alert('图片不能超过3张')
              return
            }
          }
          wx.chooseImage({
            count: 3 - currentSize, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            // sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              self.images.localId = self.images.localId.concat(res.localIds)
              if (window.__wxjs_is_wkwebview) {
                self.isIOS = true

                function readImages () {
                  wx.getLocalImgData({
                    localId: self.images.localId[currentSize],
                    success: function (res) {
                      var localData = res.localData
                      localData = localData.replace('jgp', 'jpeg')
                      self.images.iosLocalId.push(localData)
                      currentSize++
                      if (currentSize < self.images.localId.length) {
                        readImages()
                      }
                    },
                    fail: (res) => {
                      alert(res.errMsg)
                    }
                  })
                }

                readImages()
              }
              self._upload(currentSize)
            },
            fail: (err) => {
              console.log(err)
            }
          })
        }
      },
      _upload (i) {
        // var localId = localIds.shift()
        wx.uploadImage({
          localId: this.images.localId[i], // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: (res) => {
            i++
            this.serverId.push(res.serverId) // 返回图片的服务器端ID
            if (i < this.images.localId.length) {
              this._upload(i)
            }
          }
        })
      },
      delImage (index) {
        this.images.localId.splice(index, 1)
        this.serverId.splice(index, 1)
      },
      delImageIOS (index) {
        this.images.iosLocalId.splice(index, 1)
        this.images.localId.splice(index, 1)
        this.serverId.splice(index, 1)
      },
      preview (index) {
        wx.previewImage({
          current: this.images.localId[index], // 当前显示图片的http链接
          urls: this.images.localId // 需要预览的图片http链接列表
        })
      },
      getContent (content) {
        this.content = content
      },
      submitCheck (categoryId, liftNum, resolvent, serverId, relatedId) {
        if (!this.content) {
          Toast({
            message: '描述内容不能为空',
            position: 'middle',
            duration: 1000
          })
          return
        }
        submitEveryCheck(categoryId, liftNum, resolvent, serverId, relatedId).then(res => {
          if (res.code === 200) {
            this._getCheckContent()
          }
          if (res.code === 401) {
            Toast({
              message: res.data,
              position: 'middle',
              duration: 1000
            })
          }
        })
      },
      resetEveryCheck (everyCheckId, resolvent, serverId, img) {
        editVeryCheck(everyCheckId, resolvent, serverId, img).then(res => {
          if (res.code === 200) {
            this._getCheckContent()
          }
        })
      }
    },
    watch: {
      // content: function (newData, oldData) {
      //   if (newData != oldData) {
      //     this.showReSumbit = true
      //   }
      // },
      // serverId: function (newData, oldData) {
      //   if (newData != oldData) {
      //     this.showReSumbit = true
      //   }
      // }
    }
  }
</script>

<style lang="scss">
  .start-check {
    padding-top: 40px;
    position: relative;
    .theme {
      font-size: 15px;
      height: 44px;
      line-height: 44px;
      margin: 0 10px;
    }
    .back {
      position: absolute;
      width: 42px;
      height: 42px;
      line-height: 42px;
      opacity: 0;
      z-index: 668;
      // background-color: #ccc;
      top: 0px;
      left: 0;
    }
    .wrapper {
      margin: 0 10px;
      .img_size {
        display: inline-block;
        position: relative;
        width: 25%;
        // .desc{
        //   outline: none;
        //   border: none;
        //   font-size: 14px;
        //   margin-left: 10px;
        //   padding-top: 20px;
        // }
        .picture {
          width: 55px;
          height: 55px;
          float: left;
          border-radius: 4px;
          background-color: #ccc;
          background-repeat: no-repeat;
          background-size: cover;
        }
        .remove {
          position: absolute;
          top: -7px;
          left: 45px;
          width: 16px;
          height: 16px;
          z-index: 11;
          line-height: 16px;
          text-align: center;
          border-radius: 50%;
          background-color: red;
          color: #fff;
          font-size: 15px;
        }
      }
      .pic-desc-wrapper {
        position: relative;
        padding-bottom: 10px;
        .desc {
          position: relative;
          padding-right: 10px;
          padding-top: 10px;
          textarea {
            width: 100%;
            outline: none;
            border: none;
            height: 62px;
            resize: none;
            background-color: rgb(242, 242, 242);
            border-radius: 5px;
            padding: 5px;
            font-size: 14px;
          }
          .count {
            position: absolute;
            right: 5px;
            bottom: 5px;
            color: #0078de;
          }
        }
        .limit {
          color: #999;
        }
        .line {
          width: 25%;
          padding-bottom: 10px;
          float: left;
        }
        .input-container {
          margin-bottom: 10px;
          display: inline-block;
        }
        .mint-button {
          height: 22px;
        }
        .mint-button--normal {
          padding: 0 10px;
          font-size: 12px;
        }
        .btn {
          margin-top: 0px;
          position: absolute;
          bottom: 90px;
          right: 0;
        }
        .title {
          color: rgb(84, 84, 84);
          margin: 10px 0;
          font-size: 14px;
        }
        .pic-desc {
          padding-top: 10px;
          .pic {
            font-size: 0;
            vertical-align: middle;
            margin-right: 5px;
          }
          .desc {
            font-size: 14px;
            color: #888;
          }
        }
      }
    }
    .mint-cell {
      min-height: 44px;
    }
  }
</style>
